using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
namespace Microsoft.Phone.Controls.Primitives
{
	public class TemplatedItemsControl<T> : ItemsControl where T : FrameworkElement, new()
	{
		private readonly Dictionary<object, T> _itemToContainer = new Dictionary<object, T>();
		private readonly Dictionary<T, object> _containerToItem = new Dictionary<T, object>();
		public static readonly DependencyProperty ItemContainerStyleProperty = DependencyProperty.Register("ItemContainerStyle", typeof(Style), typeof(TemplatedItemsControl<T>), null);
		public Style ItemContainerStyle
		{
			get
			{
				return base.GetValue(TemplatedItemsControl<T>.ItemContainerStyleProperty) as Style;
			}
			set
			{
				base.SetValue(TemplatedItemsControl<T>.ItemContainerStyleProperty, value);
			}
		}
		protected override bool IsItemItsOwnContainerOverride(object item)
		{
			return item is T;
		}
		protected override DependencyObject GetContainerForItemOverride()
		{
			T t = Activator.CreateInstance<T>();
			this.ApplyItemContainerStyle(t);
			return t;
		}
		protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
		{
			this.ApplyItemContainerStyle(element);
			base.PrepareContainerForItemOverride(element, item);
			this._itemToContainer.set_Item(item, (T)((object)element));
			this._containerToItem.set_Item((T)((object)element), item);
		}
		protected override void ClearContainerForItemOverride(DependencyObject element, object item)
		{
			base.ClearContainerForItemOverride(element, item);
			this._itemToContainer.Remove(item);
			this._containerToItem.Remove((T)((object)element));
		}
		protected virtual void ApplyItemContainerStyle(DependencyObject container)
		{
			T t = container as T;
			if (t != null)
			{
				if (t.ReadLocalValue(FrameworkElement.StyleProperty) == DependencyProperty.UnsetValue)
				{
					Style itemContainerStyle = this.ItemContainerStyle;
					if (itemContainerStyle != null)
					{
						t.set_Style(itemContainerStyle);
						return;
					}
					t.ClearValue(FrameworkElement.StyleProperty);
					return;
				}
			}
		}
		protected object GetItem(T container)
		{
			object result = null;
			if (container != null)
			{
				this._containerToItem.TryGetValue(container, ref result);
			}
			return result;
		}
		protected T GetContainer(object item)
		{
			T result = default(T);
			if (item != null)
			{
				this._itemToContainer.TryGetValue(item, ref result);
			}
			return result;
		}
	}
}
